package commonutils;

import change.Revision;
import page.Link;
import page.WikiPage;
import pageblock.PageBlock;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 02.12.11
 * Time: 15:23
 */
public class MyWikiObjectUtils {
    public static List<WikiPage> getPagesFromRevisions(final Collection<Revision> revisions) {
        final Set<WikiPage> pages = new HashSet<WikiPage>();
        for (Revision revision : revisions) {
            pages.add(revision.getWikiPage());
        }
        return MyCollectionUtils.asList(pages);
    }

    public static List<WikiPage> getPagesByInfo(final Collection<PageBlock> infos) {
        final Set<WikiPage> set = new HashSet<WikiPage>();
        for (PageBlock info : infos) {
            set.add(info.getRevision().getWikiPage());
        }
        return MyCollectionUtils.asList(set);
    }

    public static List<WikiPage> getPagesByLinks(final Collection<Link> links){
        Set<WikiPage> linkSet = new HashSet<WikiPage>();
        for(Link link : links){
            linkSet.add(link.getFrom());
            linkSet.add(link.getTo());
        }
        return MyCollectionUtils.asList(linkSet);
    }
    
    public static Map<WikiPage, Set<WikiPage>> getComponents(List<Link> links){
        final Map<WikiPage, Set<WikiPage>> map = new HashMap<WikiPage, Set<WikiPage>>();
        for(final Link link : links){
            if(map.containsKey(link.getFrom())){
                Set<WikiPage> cc = map.get(link.getFrom());
                cc.add(link.getTo());
                map.put(link.getTo(), cc);
            } else if(map.containsKey(link.getTo())){
                Set<WikiPage> cc = map.get(link.getTo());
                cc.add(link.getFrom());
                map.put(link.getFrom(), cc);
            } else {
                Set<WikiPage> cc = MyCollectionUtils.asSet(MyCollectionUtils.asListWithoutNulls(link.getTo(), link.getFrom()));
                map.put(link.getFrom(), cc);
                map.put(link.getTo(), cc);
            }
        }
        return map;
    }

    public static void retainAll(final List<Revision> allNewRevisions,final Set<WikiPage> pagesHavingLinks) {
        final Set<Revision> toRetain = new HashSet<Revision>();
        for(final Revision revision : allNewRevisions){
            if(pagesHavingLinks.contains(revision.getWikiPage())){
                toRetain.add(revision);
            }
        }
        allNewRevisions.retainAll(toRetain);
    }
}
